package org.carshared.principal;

import java.util.ArrayList;

import org.carshared.R;
import org.carshared.sqlite.DBAdapterDateTravel;
import org.carshared.sqlite.DBAdapterPassenger;
import org.carshared.sqlite.DBAdapterTravel;
import org.carshared.utils.PassengerBeen;
import org.carshared.utils.TravelBeen;

import com.google.gson.Gson;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class BaseActivity extends ActionBarActivity {
	private DrawerLayout drawerLayout;
	private ListView drawer;
	private ActionBarDrawerToggle toggle;
	
	private static final int PICK_DATA_TRAVEL_OWNER = 0;
	private static final int PICK_DATA_TRAVEL_PASSENGER = 1;
	private boolean dialogExecuted = false;
	ArrayList<TravelBeen> datos;
	private String user;
	private DBAdapterTravel dbHelper;
	private DBAdapterPassenger dbHelperPassenger;
	private DBAdapterDateTravel dbHelperDateTravel;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.content_frame);
		datos = new ArrayList<TravelBeen>();
		// Rescatamos el Action Bar y activamos el boton Home
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setTitle(
				getResources().getString(R.string.viaje) + " "
						+ getResources().getString(R.string.conductor));
		String[] opciones = { getResources().getString(R.string.conductor), getResources().getString(R.string.pasajero) };
		dbHelper = new DBAdapterTravel(this);
		dbHelperPassenger = new DBAdapterPassenger(this);
		dbHelperDateTravel = new DBAdapterDateTravel(this);
		// opciones[0] = getResources().getString(R.string.conductor);
		// opciones[1] = getResources().getString(R.string.pasajero);

		// // Declarar e inicializar componentes para el Navigation Drawer
		drawer = (ListView) findViewById(R.id.drawer);
		drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		//
		// // Declarar adapter y eventos al hacer click
		drawer.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, android.R.id.text1,
				opciones));
		//
		FragmentManager fragmentManager = getSupportFragmentManager();

		Fragment fragment = new TraveList();
		user = "owner";
		Bundle parametro = new Bundle();
		parametro.putString("user", user);
		fragment.setArguments(parametro);
		fragmentManager.beginTransaction()
				.replace(R.id.content_frame, fragment).commit();

		drawer.setItemChecked(1, true);

		drawer.setOnItemClickListener(new OnItemClickListener() {
			//
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Fragment fragment = null;
				Bundle parametro = new Bundle();
				switch (position) {
				case 0:
					fragment = new TraveList();
					user = "owner";
					parametro.putString("user", user);
					fragment.setArguments(parametro);
					getSupportActionBar().setTitle(
							getResources().getString(R.string.viaje)
									+ " "
									+ getResources().getString(
											R.string.conductor));
					break;
				case 1:
					fragment = new TraveList();
					user = "passenger";
					parametro.putString("user", user);
					fragment.setArguments(parametro);
					getSupportActionBar().setTitle(
							getResources().getString(R.string.viaje)
									+ " "
									+ getResources().getString(
											R.string.pasajero));
					break;
				}

				FragmentManager fragmentManager = getSupportFragmentManager();

				fragmentManager.beginTransaction()
						.replace(R.id.content_frame, fragment).commit();

				drawer.setItemChecked(position, true);

				drawerLayout.closeDrawer(drawer);
			}
		});
		//
		// // Integracion boton oficial
		toggle = new ActionBarDrawerToggle(this, // Activity
				drawerLayout, // Panel del Navigation Drawer
				R.drawable.ic_drawer, // Icono que va a utilizar
				R.string.app_name, // Descripcion al abrir el drawer
				R.string.app_name // Descripcion al cerrar el drawer
		) {
			public void onDrawerClosed(View view) {
				// Drawer cerrado
				// getSupportActionBar().setTitle(
				// getResources().getString(R.string.app_name));
				supportInvalidateOptionsMenu();
			}

			public void onDrawerOpened(View drawerView) {
				// Drawer abierto
				getSupportActionBar().setTitle("Menu");
				supportInvalidateOptionsMenu();
			}
		};
		//
		drawerLayout.setDrawerListener(toggle);

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		Gson gson = new Gson();
		if (requestCode != 2) {
			if (resultCode == RESULT_OK) {
				String result = data.getStringExtra("result");
				dialogExecuted = data.getBooleanExtra("executed", false);
				TravelBeen t = gson.fromJson(result, TravelBeen.class);
				if (t != null) {
					datos.add(t);
					createTravel(t);
					createPassenger(t);
				}

			}
			if (resultCode == RESULT_CANCELED) {
				// Write your code if there's no result
			}
		} else {
			if (resultCode == RESULT_OK) {
				// Actualizamos la lista
				reloadFragment();
			}
			if (resultCode == RESULT_CANCELED) {
				// Write your code if there's no result
			}
		}

	}

	public void reloadFragment() {
		// Actualizamos la lista
		Fragment fragment = new TraveList();
		Bundle parametro = new Bundle();
		parametro.putString("user", user);
		fragment.setArguments(parametro);

		FragmentManager fragmentManager = getSupportFragmentManager();

		fragmentManager.beginTransaction()
				.replace(R.id.content_frame, fragment).commit();

	}

	private void createTravel(TravelBeen t) {
		// TODO Auto-generated method stub

		// Crear viaje
		if (dbHelper.createTravel(t) == -1) {
			Toast.makeText(getApplicationContext(),
					"ERROR, Registro no guardado..", Toast.LENGTH_LONG).show();
		}

	}

	private void createPassenger(TravelBeen t) {
		// TODO Auto-generated method stub
		for (PassengerBeen p : t.getListaPasajeros()) {
			dbHelperPassenger.createPassenger(p);
		}
	}

	//
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		return true;

	}

	//
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case R.id.nuevoViaje:
			if ("owner".equals(user)) {
				Intent i = new Intent(this, NewTravelOwnerActivity.class);

				startActivityForResult(i, PICK_DATA_TRAVEL_OWNER);
			} else {
				Intent i = new Intent(this, NewTravelPassengerActivity.class);
				startActivityForResult(i, PICK_DATA_TRAVEL_PASSENGER);
			}
			break;
		default:
			if (toggle.onOptionsItemSelected(item)) {
				return true;
			}
			break;

		}
		return true;
	}

	//
	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		toggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		toggle.onConfigurationChanged(newConfig);
	}
}
